package cn.fscode.code.generator.repository;

import cn.fscode.code.generator.assembly.DatasourceConfigAssembly;
import cn.fscode.code.generator.mapper.DatasourceConfigMapper;
import cn.fscode.code.generator.model.po.DatasourceConfigPO;
import cn.fscode.code.generator.model.req.DatasourceConfigQueryReq;
import cn.fscode.code.generator.model.resp.DatasourceResp;
import cn.fscode.commons.core.page.PageDomain;
import cn.fscode.commons.core.page.TableSupport;
import cn.fscode.commons.tool.core.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author shenguangyang
 */
@Repository
public class DatasourceConfigRepository extends ServiceImpl<DatasourceConfigMapper, DatasourceConfigPO>
        implements IService<DatasourceConfigPO> {
    @Resource
    private DatasourceConfigAssembly datasourceConfigAssembly;

    public IPage<DatasourceConfigPO> pageDataSourceConfig(DatasourceConfigQueryReq req) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        LambdaQueryWrapper<DatasourceConfigPO> queryWrapper = Wrappers.<DatasourceConfigPO>lambdaQuery()
                .eq(Objects.nonNull(req.getDbType()), DatasourceConfigPO::getDbType, req.getDbType())
                .like(StringUtils.isNotEmpty(req.getName()), DatasourceConfigPO::getName, req.getName())
                .orderByDesc(DatasourceConfigPO::getUpdateTime);
        return this.page(new Page<>(pageNum, pageSize), queryWrapper);
    }

    public List<DatasourceResp> listAllDatasourceResp() {
        LambdaQueryWrapper<DatasourceConfigPO> queryWrapper = Wrappers.<DatasourceConfigPO>lambdaQuery()
                .orderByDesc(DatasourceConfigPO::getUpdateTime);
        List<DatasourceConfigPO> list = this.list(queryWrapper);
        return list.stream().map(datasourceConfigAssembly::toDatasourceRespFrom).collect(Collectors.toList());
    }
}
